import React, { FC } from 'react';
import { Col, Row, Popover } from 'antd';
import dayjs from 'dayjs';
import { PlaneTrip, Plane } from '../types/plane.type';
import { SchedulingForm } from './SchedulingForm';

type GridType = 'scheduling' | 'ground';

type Props = {
    formatedTrips: {
        tripsMap: Record<string, PlaneTrip[]>;
        planeIds: string[];
    },
    init: () => void;
    type?: GridType;
}

const fillNumber = (number: number) => (number > 9 ? String(number) : `0${number}`);
const HOUR_24 = new Array(8).fill(0).map((_, index) => fillNumber(index * 3) + ":00");
const mins_for_1d = 24 * 60 * 60;

export const SchedulingGrid: FC<Props> = ({ formatedTrips, init, type }) => {
    return <div className='schedulingContentWrapper'>
        <Header />
        <Grid formatedTrips={formatedTrips} init={init} type={type} />
    </div>
}

const Header = () => {
    return <Row className="schedulingHeader">
        <Col flex="90px">
            <div>
                plane
            </div>
        </Col>
        <Col flex="auto">
            <Row>
                {
                    HOUR_24.map((key) => {
                        return <Col key={key} span={3} className='HeaderCell'>
                            <div>
                                {key}
                            </div>
                        </Col>
                    })
                }
            </Row>
        </Col>
    </Row>
}
type GridProps = {
    formatedTrips: {
        tripsMap: Record<string, PlaneTrip[]>;
        planeIds: string[];
    },
    init: () => void;
    type?: GridType;
}
const Grid: FC<GridProps> = ({ formatedTrips, init, type }) => {
    return <>
        {
            formatedTrips.planeIds.length === 0 && <div style={{ textAlign: "center" }} className='schedulingBody'>No scheduling trips.</div>
        }
        {
            formatedTrips.planeIds.map((planeId, index) => {
                const trips = formatedTrips.tripsMap[planeId];
                return <Row key={planeId + index} className="schedulingBody schedulingRow">
                    <Col flex="90px">
                        <div className='planeNameWrap'>
                            {trips[0]?.plane.name}
                        </div>
                    </Col>
                    <Col flex="auto" className='schedulingRowContent'>
                        <Row style={{ position: "relative", height: 30 }}>
                            {
                                trips.map((trip, index) => {
                                    return <GridCell key={(trip.id ?? 0) + index} type={type} trip={trip} afterSubmit={init} />
                                })
                            }
                        </Row>
                    </Col>
                </Row>
            })
        }
    </>
}


const getMinsBetween = (date1: string, date2: string) => {
    const diffs = dayjs(date2).diff(date1, 's');
    const mins = Math.round(diffs);
    return mins;
}

const getWidth = (date1: string, date2: string) => {
    const mins = getMinsBetween(date1, date2);
    return `${mins / mins_for_1d * 100}%`
}

const getPassTime = (date1: string, date2: string) => {
    const now = dayjs();
    const departuretime = dayjs(date1);
    const arrivetime = dayjs(date2);
    if (now.isBefore(departuretime)) {
        return 0;
    }
    if (now.isAfter(arrivetime)) {
        return arrivetime.diff(date1, 's')
    }
    return now.diff(date1, 's');
}

const getTotalTime = (date1: string, date2: string) => {
    return dayjs(date2).diff(date1, 's')
}

const getLeft = (startTime: string) => {
    const date = dayjs(startTime);
    return `${date.hour() / 24 * 100}%`
}

type ContentProps = {
    trip: PlaneTrip;
    selectedPlane: Plane;
    afterSubmit?: (trip: PlaneTrip) => void;
}

const ContentForScheduling: FC<ContentProps> = ({ trip, selectedPlane, afterSubmit }) => {
    return <div>
        <SchedulingForm
            showDelete
            buttonText={"Submit"}
            afterSubmit={afterSubmit}
            selectedPlane={selectedPlane}
            selectedTrip={trip} layout='vertical'
        />
    </div>
}

type ContentForGroundProps = {
    trip: PlaneTrip;
    selectedPlane: Plane;
}
const ContentForGround: FC<ContentForGroundProps> = ({ trip, selectedPlane }) => {
    return <div>
        <p>destination: {trip.destination}</p>
        <p>start time: {trip.departuretime}</p>
        <p>End time: {trip.arrivetime}</p>
    </div>
}

type GridCellProps = {
    trip: PlaneTrip;
    afterSubmit: () => void;
    type?: GridType;
}

const GridCell: FC<GridCellProps> = ({ trip, afterSubmit, type = 'scheduling' }) => {
    const { origin, destination, departuretime, arrivetime, plane } = trip;
    const showText = type === 'scheduling' ? `${origin} - ${destination}` : destination;
    const showTitle = type === 'scheduling' ? `Info for ${plane.name} of trip ${origin} - ${destination}` : `Info for ${plane.name} of grounding in ${destination}`;
    const content = type === 'scheduling' ? <ContentForScheduling
        trip={trip}
        selectedPlane={plane}
        afterSubmit={afterSubmit}
    /> : <ContentForGround trip={trip} selectedPlane={plane} />
    const totalTime = getTotalTime(departuretime, arrivetime);
    const passTime = getPassTime(departuretime, arrivetime);
    return <Popover
        trigger="click"
        content={content}
        title={showTitle}
    >
        <div
            className='schedulingContent'
            style={{
                left: getLeft(departuretime),
                width: getWidth(departuretime, arrivetime),
                background: "#1677ff"
            }}>
            <div style={{ width: `${passTime / totalTime * 100}%` }} className='schedulingContentPass'></div>
            <div style={{ width: `${(totalTime - passTime) / totalTime * 100}%`, left: `${passTime / totalTime * 100}%` }} className='schedulingContentWill'></div>
            <span className='positionCenter'>{showText}</span>
        </div>
    </Popover>
}
